<template>
    <div>
      <vue-esign ref="esign" :width="1000" :height="400" style="border: 1px solid black;" :isCrop="isCrop" :lineWidth="lineWidth" :lineColor="lineColor" :bgColor.sync="bgColor" />
      <button @click="handleReset">清空画板</button>
      <button @click="handleGenerate">生成图片</button>
      <button @click="drawProdPicture">合成图片</button>
      <div style="border: solid 2px red">
      <img :src="resultImg">
      </div>
      <img :src="makePic">
    </div>
  
  </template>
  <script>
    /**
     * npm install vue-esign --save
     *
     * https://github.com/JaimeCheng/vue-esign
     */
    import Vue from 'vue';
    //引入组件
    import vueEsign from 'vue-esign';
    //这里就是我猫咪照片的地址
    // import bgPic from '@/assets/images/demo.jpg';
    Vue.use(vueEsign)
    export default {
      data () {
        return {
          lineWidth: 6,
          lineColor: '#000000',
          bgColor: '',
          //签名图
          resultImg: '',
          isCrop: false,
          //底图
          bgPic: "https://cdn.wakoohome.com/2023.6.21%E7%BC%96%E7%A8%8B%E5%88%86%E7%B1%BB%E8%A7%86%E9%A2%91%E5%8F%8A%E5%9B%BE%E7%89%87/Scratch/9%E5%B2%81%E5%B0%81%E9%9D%A2%E5%92%8C%E4%BB%8B%E7%BB%8D%E5%9B%BE/Scratch65-%E5%93%A5%E5%BE%B7%E5%B7%B4%E8%B5%AB%E7%8C%9C%E6%83%B3%E5%B0%81%E9%9D%A2.png",
          makePic: ''
        }
      },
      methods: {
        handleReset () {
          this.$refs.esign.reset()
        },
        handleGenerate () {
          this.$refs.esign.generate().then(res => {
            this.resultImg = res
            console.log(res);
  
          }).catch(err => {
            alert(err) // 画布没有签字时会执行这里 'Not Signned'
          })
        },
        drawProdPicture () {
          let img1 = new Image()
          img1.src = this.bgPic
          img1.width = 1496
          img1.height = 866
          img1.setAttribute('crossOrigin', 'anonymous')
          let canvas = document.createElement("canvas")
          let context = canvas.getContext("2d")
          canvas.width = 1500
          canvas.height = 866
          let img2 = new Image()
          let flag = true
          // 将 img1 加入画布
          img1.onload = () => {
            context.drawImage(img1, 0, 0, 1495, 866)
            img2.src = this.resultImg
            img2.setAttribute('crossOrigin', 'anonymous')
            img2.width = 120
            img2.height = 50
            if (flag) {
              flag = false
            } else {
              let src = canvas.toDataURL()
              this.makePic = src
            }
          }
          // 将 img2 加入画布
          img2.onload = () => {
            context.drawImage(img2, 1200, 166, 300, 200) //更改签名照片合并位置和展示大小
            if (flag) {
              flag = false
            } else {
              let src = canvas.toDataURL('image/png')
              this.makePic = src
            }
          }
        }
      }
    }
  </script>